/**
 * 
 */
package com.et114.modules.reg;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.acegisecurity.providers.encoding.Md5PasswordEncoder;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.et114.components.validCode.AuthCodeImg;
import com.et114.components.validCode.ImageCaptchaServlet;
import com.et114.core.action.BaseDispatchAction;
import com.et114.core.common.AppContext;
import com.et114.modules.cust.services.IMng_CustService;
import com.et114.modules.cust.services.Mng_CustServiceImp;
import com.et114.modules.cust.vo.CustBaseVo;
import com.et114.modules.org.services.OrgFactory;
import com.et114.modules.org.services.UserManager;
import com.et114.modules.org.vo.UserVo;
import com.et114.modules.products.commons.Const;
import com.et114.modules.products.commons.PorJsonObj;
import com.et114.modules.products.commons.SessionUser;
import com.et114.modules.products.commons.ViewsMessageManager;

/*
 * @author guanhw
 */
public class RegAction extends BaseDispatchAction {
	private Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();
	public  ActionForward reg4View( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		
		String referer = request.getHeader( "referer" );
		if ( referer == null  ){
			logger.warn ( "referer is null !" )  ;
			return new ActionForward( "/reg.html" , true ) ; 
		}
		
		HttpSession session = request.getSession ( ) ; 
		Locale locale = Locale.SIMPLIFIED_CHINESE ;
		Object obj_l =  session.getAttribute ( Const.SESSION_LANGUAGE_KEY ) ;
		Object obj_c =  session.getAttribute ( Const.SESSION_COUNTRY_KEY ) ;
		if (  obj_l != null && obj_c != null  ) 
			locale = new Locale( obj_l.toString ( ) , obj_c.toString ( ) ) ; 
		
		

		RegForm regForm = ( RegForm ) form ; 
		
		
		//PARAMS
		String firstName = regForm.getFirstName ( ) ; 
		String lastName = regForm.getLastName ( ) ; 
		String userName = regForm.getUserName ( ) ; 
		String password = regForm.getPassword ( ) ; 
		String repassword = regForm.getRePassword ( ) ; 
		String email = regForm.getEmail ( ) ; 
		String phone = regForm.getPhone ( ) ; 
		
		request.setAttribute ( "firstName" , firstName ) ; 
		request.setAttribute ( "lastName" , lastName ) ; 
		request.setAttribute ( "userName" , userName ) ; 
		request.setAttribute ( "email" , email ) ; 
		request.setAttribute ( "phone" , phone ) ; 
		//valider 
		Map < String , String > errors = new HashMap < String , String > ( );
		if ( firstName == null || firstName.trim ( ).length ( ) < 1 )
			errors.put ( "errorFirstName" , ViewsMessageManager.get ( locale )
					.getMessage ( "check.firstName.isNull" ) );
		
		if ( lastName == null || lastName.trim ( ).length ( ) < 1 )
			errors.put ( "errorLastName" , ViewsMessageManager.get ( locale )
					.getMessage ( "check.lastName.isNull" ) );
		
		if ( userName == null || userName.trim ( ).length ( ) < 8 || userName.trim ( ).length ( ) > 40 )
			errors.put ( "errorUserName" , ViewsMessageManager.get ( locale )
					.getMessage ( "check.userName.isNull" ) );
		
		if ( password == null || password.trim ( ).length ( ) < 8 )
			errors.put ( "errorPassword" , ViewsMessageManager.get ( locale )
					.getMessage ( "check.password.isNull" ) );
		
		if ( repassword == null || repassword.trim ( ).length ( ) < 8 )
			errors.put ( "errorRePassword" , ViewsMessageManager.get ( locale )
					.getMessage ( "check.repassword.isNull" ) );
		
		if ( repassword != null && password != null
				&& ! repassword.equals ( password ) )
			errors.put ( "errorRePassword" , ViewsMessageManager.get ( locale )
					.getMessage ( "check.repassword.noMac" ) );
		
		if ( email == null )
			errors.put ( "errorEmail" , ViewsMessageManager.get ( locale )
					.getMessage ( "check.repassword.noMac" ) );
		
		if ( phone == null )
			errors.put ( "errorPhone" , ViewsMessageManager.get ( locale )
					.getMessage ( "check.phone.isNull" ) );
		
		
		
		
		String vcode = request 
			.getParameter ( ImageCaptchaServlet.ACEGI_SECURITY_FORM_VALIDCODE_KEY ); 
		if ( vcode == null || session.getAttribute ( ImageCaptchaServlet.ACEGI_SECURITY_FORM_VALIDCODE_KEY ) == null )
			errors.put ( "errorCode" , ViewsMessageManager.get ( locale )
					.getMessage ( "login.error.vcode" ) );
		

		
		
		if ( vcode != null
				&& session.getAttribute ( ImageCaptchaServlet.ACEGI_SECURITY_FORM_VALIDCODE_KEY ) != null 
				&& !vcode.equals ( session.getAttribute ( ImageCaptchaServlet.ACEGI_SECURITY_FORM_VALIDCODE_KEY ) )) {
			errors.put ( "errorCode" , ViewsMessageManager.get ( locale )
					.getMessage ( "login.error.vcode" ) );		

		}
		if ( errors.size ( ) > 0  ) {
			request.setAttribute ( "errorsMap" , errors ) ;
			return mapping.findForward ( "reg" )  ;
		}
		
		
		UserManager userBean  = OrgFactory.getUserManager ( ) ; 
		boolean has = userBean.checkExistsUserByLoginName ( userName ) ; 
		if ( !has  ) {
			errors.put( "errorUserName" ,  ViewsMessageManager.get ( locale ).getMessage ( "check.userName.exists" , request.getLocale ( ) ) );
			request.setAttribute ( "errorsMap" , errors ) ;
			return mapping.findForward ( "reg" ) ;
		} 
			
		else{
			UserVo user = new UserVo( ) ; 
			user.setLoginName ( userName ) ; 
			user.setPassword ( md5PasswordEncoder.encodePassword ( password , null )  ) ; 
			user.setUserFlag ( String.valueOf ( Const.USER_MANAGER_USERFLG_REG ) ) ;
			user.setWorkFlg ( Boolean.valueOf ( true ) ) ;
			user.setCrtUser ( Long.valueOf ( -Const.USER_MANAGER_USERFLG_REG ) ) ; 

			Reg_ServiceImp reg=(Reg_ServiceImp)super.getBean ( "reg_ServiceImp" );
			CustBaseVo vo = new CustBaseVo();
			vo.setFamname ( firstName );
			vo.setCustname ( lastName );
			vo.setEmail ( email );
			vo.setMobileno ( phone );
			reg.insertRegUser ( user,vo );
			
			
			session.removeAttribute ( ImageCaptchaServlet.ACEGI_SECURITY_FORM_VALIDCODE_KEY  ) ;
		}
		return new ActionForward( "/regSuccess.html" , true  ) ;
	}
	
	public  ActionForward check4View( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		RegForm regForm = ( RegForm ) form ; 
		String userName = regForm.getUserName ( ) ; 
		UserManager userBean  = OrgFactory.getUserManager ( ) ; 
		boolean has = userBean.checkExistsUserByLoginName ( userName ) ; 
		JSONObject jsonObj = new JSONObject ( );
		jsonObj.element ( "check" , has ) ; 
		return PorJsonObj.response ( response , jsonObj ) ; 
	}
	
	
	public  ActionForward login4View( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		response.setContentType ( "text/html;charset="
				+ AppContext.getFrameWorkPropertiesBean ( ).getCharSet ( ) );
		// PARAMS
		HttpSession session = request.getSession ( ) ; 
		
        if ( session.getAttribute ( "session_login_views" ) == null )
        	return new ActionForward( "/login.html" , true ) ;
		
        
		String referer = request.getHeader( "referer" );
		if ( referer == null  ){
			logger.warn ( "referer is null !" )  ;
			return new ActionForward( "/login.html" , true ) ; 
		}
		
		
		RegForm regForm = ( RegForm ) form ; 
		String userName = regForm.getUserName ( ) ; 
		String password = regForm.getPassword ( ) ; 
		
		
		String vcode = request 
				.getParameter ( AuthCodeImg.ACEGI_SECURITY_FORM_VALIDCODE_KEY );
		
		if ( vcode == null )
			return PorJsonObj.response ( response , PorJsonObj.error ( "vcode" ) );
		if ( session.getAttribute ( AuthCodeImg.ACEGI_SECURITY_FORM_VALIDCODE_KEY ) == null )
			return PorJsonObj.response ( response , PorJsonObj.error ( "vcode" ) );
		
		if ( ! session.getAttribute (
				AuthCodeImg.ACEGI_SECURITY_FORM_VALIDCODE_KEY ).equals ( vcode ) )
			return PorJsonObj.response ( response , PorJsonObj.error ( "vcode" ) );

		session.removeAttribute ( AuthCodeImg.ACEGI_SECURITY_FORM_VALIDCODE_KEY ) ;
		//BIS
		JSONObject jsonObj = new JSONObject ( );
		if ( StringUtils.isEmpty( userName )  || StringUtils.isBlank( userName )  ) {
			return PorJsonObj.response ( response , PorJsonObj.error ( ) ) ; 
		}
		if ( StringUtils.isEmpty( password )  || StringUtils.isBlank( password )  ) {
			return PorJsonObj.response ( response , PorJsonObj.error ( ) ) ; 
		}		
		UserManager userBean  = OrgFactory.getUserManager ( ) ; 
		UserVo user = userBean.loadUserByLoginName( userName ) ; 
		
		
		
		
		if ( user == null ) 
			return PorJsonObj.response ( response , PorJsonObj.error ( ) ) ; 
		else {
			if ( !user.getWorkFlg ( ) )
				return PorJsonObj.response ( response , PorJsonObj.error ( ) ) ; 
			
			if ( !String.valueOf ( Const.USER_MANAGER_USERFLG_REG ).equals ( user.getUserFlag ( ) ) ) 
				return PorJsonObj.response ( response , PorJsonObj.error ( ) ) ; 
			
			if ( md5PasswordEncoder.encodePassword ( password , null ) .equals ( user.getPassword ( ) ) ) {
				IMng_CustService mng_CustService= ( Mng_CustServiceImp ) getBean ( "mng_CustService" );
				CustBaseVo cust = new CustBaseVo ( );		
				cust.setReguserid ( user.getUserId ( ).intValue ( ) );
				cust = mng_CustService.loadCust ( cust );
				Integer custId=null;
				if(cust == null){//无? 新建
					cust = new CustBaseVo ( );		
					cust.setReguserid ( user.getUserId ( ).intValue ( ) );
					custId=mng_CustService.newEmptyCust ( cust );
				}else{
					custId=cust.getCustid ( );
				}
				
				SessionUser sessionUser = new SessionUser( ) ;
				PropertyUtils.copyProperties ( sessionUser , user ) ; 
				sessionUser.setCustId ( custId );
				sessionUser.setLoginName ( userName );
				session.setAttribute ( Const.SESSION_USER_KEY , sessionUser ) ; 
				session.removeAttribute ( "LAST_URL"); 
				try{
					//saveSessionShoppingCarToDB(request,user.getUserId ( ).toString ( ),custId);//登录后初始化购物车
					session.removeAttribute ( "session_login_views" ) ;
				}catch(Exception e){e.printStackTrace ( );}
				
				jsonObj.element ( "login" , "success" ) ; 
				
			}
			else 
				return PorJsonObj.response ( response , PorJsonObj.error ( ) ) ; 
		}
		
		return PorJsonObj.response ( response , jsonObj ) ; 
	}
	
	public  ActionForward logout( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		HttpSession session = request.getSession ( ) ;
		session.removeAttribute ( Const.SESSION_USER_KEY );
		//session.removeAttribute ( BIZ.SESSIOIN_SHOPINGCAR );
		response.sendRedirect ( "index.html" );
		return null;
	}
	
	public ActionForward modPass( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		HttpSession session = request.getSession ( ) ;
		SessionUser sessionUser = ( SessionUser )session.getAttribute ( Const.SESSION_USER_KEY );
		RegForm regForm = ( RegForm ) form ; 
		Map < String , String > errors = new HashMap < String , String > ( );
		if ( sessionUser != null  ) {
			Long userId = sessionUser.getUserId ( ) ;
			String cpassword = sessionUser.getPassword ( ) ; 
			//PARAMS
			String oldpass = request.getParameter ( "oldpass" ) ; 
			if ( oldpass == null || "".equals ( oldpass.trim ( ) )  ) 
				errors.put ( "oldpass" , "error" ) ;
				
			if ( oldpass != null ) {
				String oldpassmd5 = md5PasswordEncoder.encodePassword ( oldpass , null )  ; 
				if ( !sessionUser.getPassword ( ).equals ( oldpassmd5 ) )
					errors.put ( "oldpass" , "error" ) ;
			}
			String pass = regForm.getPassword ( );
			String repass = regForm.getRePassword ( );
			if ( pass != null && repass != null && ! "".equals ( pass.trim ( ) )
					&& pass.equals ( repass ) && ! pass.equals ( cpassword ) ) {
				updatePassword4View ( userId , pass );
			}
			else 
				errors.put ( "do" , "error" ) ;
				
			if ( errors.size ( ) ==  0 ) {
				request.setAttribute ( "mods" , "true" ) ;
			}
			else
				request.setAttribute ( "errorsMap" , errors ) ;			
		}

		
		return new ActionForward( "/views/myet/myet_modpass.jsp"  ) ;
	}
	
	/**
	 * 个人用户密码修改
	 * 
	 * @param uservo
	 */
	public synchronized void updatePassword4View ( Long userId , String password ) {
		UserVo uservo = OrgFactory.getUserManager ( ).getUserById ( userId ) ; 
		if ( uservo != null ) {
			uservo.setPassword ( md5PasswordEncoder.encodePassword ( password , null ) );
			OrgFactory.getUserManager ( ).updateUser ( uservo ) ; 
		}
	}		
	
	/*
	 * private boolean saveSessionShoppingCarToDB(HttpServletRequest
	 * request,String userid,Integer custid) throws Exception{ IMyEt_UCenterDao
	 * m_IMyEt_UCenterDao = ( MyEt_UCenterDaoImp ) getBean (
	 * "m_IMyEt_UCenterDao" ); IMyEt_UCenterService m_IMyEt_UCenterService = (
	 * MyEt_UCenterServiceImp ) getBean ( "m_IMyEt_UCenterService" );
	 * HttpSession session = request.getSession ( ); Object obj =
	 * session.getAttribute ( BIZ.SESSIOIN_SHOPINGCAR ); if ( obj != null) {
	 * List < MyEtOrder_VO > sList = ( List ) obj; for ( MyEtOrder_VO ord :
	 * sList ) {// 无需事务控制 MyEtOrder_VO shop = new MyEtOrder_VO ( );
	 * shop.setUserid ( userid ); shop.setCustid ( custid.toString ( ) );
	 * shop.setItemid ( ord.getItemid ( ) ); shop.setItemtype ( ord.getItemtype
	 * ( ) ); shop.setSerpid ( ord.getSerpid ( ) ); shop.setSupid ( ord.getSupid
	 * ( ) ); shop.setItemkindID ( ord.getItemkindID ( ) ); shop.setItemkind (
	 * ord.getItemkind ( ) );
	 * 
	 * List < MyEtOrder_VO > carList = m_IMyEt_UCenterDao.queryList_ET_SHOPCAR (
	 * shop );
	 * 
	 * if ( carList.size ( ) > 0 ) { MyEtOrder_VO pvo = carList.get ( 0 );
	 * pvo.setSalenum ( carList.get ( 0 ).getSalenum ( ) .intValue ( ) + 1 );
	 * m_IMyEt_UCenterDao.update_ET_SHOPCAR ( pvo );
	 * 
	 * } else { m_IMyEt_UCenterDao.insert_ET_SHOPCAR ( shop ); }
	 * 
	 * } } MyEtOrder_VO shop = new MyEtOrder_VO ( ); shop.setUserid ( userid );
	 * shop.setCustid ( custid.toString ( ) ); shop.setCountry_ZH (
	 * super.getSessionLanguage ( request ) ); List < MyEtOrder_VO > carList =
	 * m_IMyEt_UCenterService .queryList_ET_SHOPCAR ( shop );
	 * session.setAttribute ( BIZ.SESSIOIN_SHOPINGCAR,carList ); return true; }
	 */
}
